import React, { useState, useRef, useEffect } from 'react'
import { Row, Col, Button, Select, Space, Pagination, ConfigProvider, message, Modal, Input, Radio } from 'antd';
import { DeleteOutlined, UnlockOutlined, RotateRightOutlined } from '@ant-design/icons';
import zhCN from 'antd/lib/locale/zh_CN';
import store from './../../../redux/store';
import { AsyncTableDataAction } from '../../../redux/action/customerAction/tableData';
import DelateCustomer from './../delateCustomer/DelateCustomer';
import { AsyncGetOptionAction } from '../../../redux/action/customerAction/option';
import myAxios from '../../../utils/myAxios';
const { Option } = Select;


export default function CustomerBottom() {
  const [selvalue, setselvalue] = useState(null);
  const [batchDeleteModal, setbatchDeleteModal] = useState(false);
  const [isShowDeleta, setisShowDeleta] = useState(false);
  const [isShowToSeas, setisShowToSeas] = useState(false);
  const [isProtect, setisProtect] = useState(false);
  const [count, setcount] = useState(0);

  const mySelect = useRef()
  const myreson = useRef()
  const { TextArea } = Input;
  //单选
  const [value, setValue] = useState(1);
  const [staffList, setstaffList] = useState([]);
  //用一个状态在存储批量删除的客户数据，用于props传值
  const [userInfo, setuserInfo] = useState([]);
  // 转移到公海的原因
  const [reason, setreason] = useState('');
  // 转移到公海去的客户数组
  const [toSeastempArr, settoSeastempArr] = useState([]);

  useEffect(() => {
    // 获取员工列表下拉的异步action
    store.dispatch(AsyncGetOptionAction())
    let fn = store.subscribe(() => {
      setcount(store.getState().customerReducer.tableCountReducer);
      setstaffList(store.getState().customerReducer.optionReducer.employee);
    })
    return () => {
      fn()
    }
  }, [])


  function handleChange(value) {
    // console.log(`selected ${value}`);
    setselvalue(value)
  }

  function cancelDeleta() {
    setisShowDeleta(false)
  }
  function cancelToSeas() {
    setisShowToSeas(false)
  }

  function cancelProtect() {
    setisProtect(false)
  }
  // 点击转移
  const transfer = () => {
    // 从redux里面拿到勾选客户的信息，循环遍历出来客户的id
    const transferInfo = store.getState().customerReducer.tableCheckReducer
    // console.log(transferInfo);
    let tempArr = []
    // tempArr存放被勾选的客户的id
    if (transferInfo.length == 0) {
      message.warning({
        content: '请选择要转移的客户',
        style: {
          color: 'red',
        },
      });
    } else if (selvalue == null) {
      message.warning({
        content: '请选择要转移给的对象',
        style: {
          color: 'red',
        },
      });
    } else {
      transferInfo.forEach(item => {
        tempArr.push(item.key)
      });

      // console.log(tempArr); //被勾选的客户的id
      // console.log(selvalue); //转移给的业务员id
      //发起转移请求
      myAxios({
        method: 'post',
        url: '/customer/updateTransferCustomer',
        data: { employeeId: selvalue, id: tempArr }
      })
        .then(res => {
          // console.log(res.data);
          if (res.data.code == 200) {
            message.success(res.data.msg)
          } else {
            message.error(res.data.msg)
          }
        })


    }


  }

  //点击批量删除
  const batchDelete = () => {
    // 从redux里面拿到勾选客户的信息，循环遍历出来客户的id
    const batchDeleteInfo = store.getState().customerReducer.tableCheckReducer
    if (batchDeleteInfo.length == 0) {
      setbatchDeleteModal(true)
    } else {
      // 删除操作
      console.log(batchDeleteInfo);
      setuserInfo(batchDeleteInfo)
      setisShowDeleta(true)
    }
  }

  // 点击转入公海
  const toSeas = () => {
    let tempArr = []
    const batchDeleteInfo = store.getState().customerReducer.tableCheckReducer
    if (batchDeleteInfo.length == 0) {
      setbatchDeleteModal(true)
    } else {
      setisShowToSeas(true)
      batchDeleteInfo.forEach(item => {
        tempArr.push(item.key)
      });
      settoSeastempArr(tempArr)
    }
  }

  //确认转移公海的方法
  const okToSeas = () => {
    // console.log(reason);
    // console.log(toSeastempArr);
    //发起转移到公海请求
    myAxios({
      method: 'post',
      url: '/customer/updateTransferSeaCustomer',
      data: { id: toSeastempArr, remark: reason }
    })
      .then(res => {
        // console.log(res.data);
        if (res.data.code == 200) {
          message.success(res.data.msg)
          //成功转移到公海后，需要刷新一下table数据
          store.dispatch(AsyncTableDataAction())
          //关闭模态框
          setisShowToSeas(false)
        } else {
          message.error(res.data.msg)
        }
      })
  }

  // 点击保护期例外设置
  const protect = () => {
    const batchDeleteInfo = store.getState().customerReducer.tableCheckReducer
    if (batchDeleteInfo.length == 0) {
      setbatchDeleteModal(true)
    } else {
      setisProtect(true)
    }
  }


  const handleOk = () => {
    setbatchDeleteModal(false);
  };

  const handleCancel = () => {
    setbatchDeleteModal(false);
  };


  const onChangeRadio = e => {
    console.log('radio checked', e.target.value);
    setValue(e.target.value);
  };
  //页码改变
  const changePage = (page, pageSize) => {
    console.log(page);
    if (page==0) return
    // console.log(pageSize);
    //当页码改变，提交获取table数据的异步action
    store.dispatch(AsyncTableDataAction(page, pageSize, 0, 0, 1, '', 0))
  }
  //每页条数发生改变
  const sizeChange = (current, size) => {
    store.dispatch(AsyncTableDataAction(1, size, 0, 0, 1, '', 0))
  }
  return (
    <>
      <ConfigProvider locale={zhCN}>
        <Row style={{ marginTop: '20px' }} >
          {/* 底部左边 */}
          <Col span={12} >
            <Space>
              <div style={{ width: '120px' }}>您可以将选中信息 </div>
              <Select ref={mySelect} placeholder='请选择' style={{ width: 140 }} onChange={handleChange}>

                {
                  staffList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)
                }
              </Select>
              <Button style={{ backgroundColor: '#486B7B', color: 'white' }} size='small'
                onClick={() => { transfer() }}
              >转移</Button>
              <Button onClick={() => { batchDelete() }} style={{ backgroundColor: '#505152', color: 'white' }} size='small' icon={<DeleteOutlined />}>批量删除</Button>
              <Button onClick={() => { toSeas() }} style={{ backgroundColor: '#469F8E', color: 'white' }} size='small' icon={<RotateRightOutlined />}>转入公海</Button>
              <Button onClick={() => { protect() }} type='primary' size='small' icon={<UnlockOutlined />}

              >保护期例外设置</Button>

            </Space>
          </Col>
          {/* 底部右边 */}
          <Col span={12}>
            <div style={{ textAlign: 'right' }}>
              <Pagination

                defaultPageSize={7}
                pageSizeOptions={[7, 10, 15, 20]}
                total={count}
                showSizeChanger
                showQuickJumper
                showTotal={total => `共 ${total} 条`}
                onChange={changePage}
                onShowSizeChange={sizeChange}
              />
            </div>
          </Col>
        </Row>
      </ConfigProvider>

      <Modal
        closable={false}
        width={250}
        style={{ top: 200 }}
        footer={[
          // 定义右下角 按钮的地方 可根据需要使用 一个或者 2个按钮
          <Button key="submit" type="primary" onClick={() => { handleOk() }}  >
            确认
          </Button>,]}
        title='信息' visible={batchDeleteModal} onCancel={handleCancel}>
        您没有选中任何客户！
      </Modal>

      {/* 删除客户的模态框 */}
      <Modal visible={isShowDeleta} onCancel={cancelDeleta}
        width={500}
        footer={[]}
      >
        <DelateCustomer
          userInfo={userInfo}
          setisShowDeleta={setisShowDeleta}
        />
      </Modal>

      {/* 转入的模态框 */}
      <Modal visible={isShowToSeas} onCancel={cancelToSeas}
        width={500}
        footer={[]}
      >
        <h3 >转入公海</h3>
        <div style={{ fontWeight: 'bolder', textAlign: 'center' }}>转入公海 原因</div>
        <TextArea onChange={() => {
          setreason(myreson.current.resizableTextArea.textArea.value)
        }} ref={myreson} style={{ margin: '10px 10px 10px 0px' }} rows={3} />

        <div style={{ margin: '10px 10px 30px 0px' }}>已选中客户编号：{
          toSeastempArr.map(item => {
            return <span key={item}>{item},</span>
          })
        } </div>
        <div style={{ textAlign: 'center', borderTop: '1px dashed gray', padding: 20 }}>
          <Space>
            <Button style={{ width: 100 }} size='midle' type="primary" htmlType="submit"
              onClick={() => {
                // setisShowToSeas(false)
                okToSeas()
              }
              }

            >
              保存
            </Button>
            <Button onClick={() => { setisShowToSeas(false) }} style={{ width: 100 }} size='midle' danger type="primary" >
              取消
            </Button>
          </Space>
        </div>
      </Modal>

      {/* 保护期例外设置模态框 */}
      <Modal visible={isProtect} onCancel={cancelProtect}
        width={500}
        footer={[]}
      >
        <h3 >保护期例外</h3>
        <div style={{ fontWeight: 'bolder', textAlign: 'center' }}>操作提示</div>

        <Radio.Group style={{ width: '100%', textAlign: 'center', paddingTop: 20 }} onChange={onChangeRadio} value={value}>
          <Radio value={1}><span style={{ color: 'red' }}>不参与保护期</span></Radio>
          <Radio value={2}><span>参与保护期</span></Radio>
        </Radio.Group>
        <div style={{ margin: '10px 10px 30px 0px' }}>已选中客户编号：<span>2</span> </div>
        <div style={{ textAlign: 'center', borderTop: '1px dashed gray', padding: 20 }}>
          <Space>
            <Button style={{ width: 100 }} size='midle' type="primary" htmlType="submit"
              onClick={() => setisProtect(false)}
            >
              保存
            </Button>
            <Button onClick={() => { setisProtect(false) }} style={{ width: 100 }} size='midle' danger type="primary" >
              取消
            </Button>
          </Space>
        </div>
      </Modal>
    </>
  )
}
